package com.lanyan.web.controller.api;

import com.alibaba.fastjson2.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.lanyan.common.annotation.RepeatSubmit;

import java.math.BigDecimal;

import com.lanyan.common.utils.SecurityUtils;
import com.lanyan.common.utils.http.HttpUtils;
import com.lanyan.common.utils.wx.WxAppletUserInfo;
import com.lanyan.framework.web.service.SysLoginService;
import com.lanyan.system.domain.Setting;
import com.lanyan.system.domain.vo.SettingVo;
import com.lanyan.system.mapper.AccountMapper;
import com.lanyan.system.service.ISettingService;
import com.lanyan.system.service.ISysConfigService;
import com.lanyan.web.core.config.WxConfig;
import io.swagger.annotations.Api;

import java.util.*;

import com.lanyan.common.core.domain.R;
import com.lanyan.common.core.domain.PageR;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import com.lanyan.common.annotation.Log;
import io.swagger.annotations.ApiOperation;
import com.lanyan.common.core.controller.BaseController;
import com.lanyan.common.core.domain.AjaxResult;
import com.lanyan.common.core.domain.R;
import com.lanyan.common.enums.BusinessType;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import springfox.documentation.annotations.ApiIgnore;
import com.lanyan.common.utils.StringUtils;
import com.lanyan.system.domain.Account;
import com.lanyan.system.domain.vo.AccountVo;
import com.lanyan.system.service.IAccountService;
import com.lanyan.common.utils.poi.ExcelUtil;
import com.lanyan.common.core.page.TableDataInfo;

/**
 * 用户Controller
 *
 * @author lanyan
 * @date 2024-11-18
 */
@RestController
@Api(tags = {"用户"})
@RequestMapping("/api/account")
public class ApiAccountController extends BaseController {
    @Autowired
    private IAccountService accountService;
    @Autowired
    private AccountMapper accountMapper;
    @Autowired
    private ISysConfigService configService;
    @Autowired
    private ISettingService settingService;
    @Autowired
    private SysLoginService loginService;

    @ResponseBody
    @GetMapping("login")
    @ApiOperation(value = "login")
    public AjaxResult login(HttpServletRequest request, String code) {
        JSONObject jsonObject = WxAppletUserInfo.getSessionKeyOropenid(
                code,
                configService.selectConfigByKey("wx.appId"),
                configService.selectConfigByKey("wx.secret")
        );
        String openId = (String) jsonObject.get("openid");
//
        HttpSession session = request.getSession();//创建session
        Object session_key = jsonObject.get("session_key");
        session.setAttribute("sessionkey",session_key);
//        openId = "oM7ur690JoYFX_RC_0VA1j7rDKBw";
        if (null == openId) {
            return  AjaxResult.error(201, "失败");
        } else {
            Map result =new HashMap();
            result.put("token",null);
            Account one = accountService.lambdaQuery().eq(Account::getDelFlag,"0").eq(Account::getOpenId,openId).one();
            if (one != null){
                String token = loginService.weChatLogin(openId);
                result.put("token",token);
                if (StringUtils.equals(one.getIsFreeze(),"1")){
                    return error("您已被冻结，请联系管理员.");
                }
            }
            result.put("openId",openId);
            result.put("account",one);
            result.put("sessionKey", session_key);
            //保存用户登录时间
            LambdaQueryWrapper<Account> accountLambdaQueryWrapper = new LambdaQueryWrapper<>();
            accountLambdaQueryWrapper.eq(Account::getOpenId,openId);
            Account account = accountMapper.selectOne(accountLambdaQueryWrapper);
            account.setUpdateTime(new Date());
            accountMapper.update(account,accountLambdaQueryWrapper);
            return AjaxResult.success(result);
        }
    }

    //注册
    @PostMapping("register")
    @ApiOperation(value = "注册")
    @ResponseBody
    @ApiImplicitParams({
            @ApiImplicitParam(name = "name", value = "姓名", dataType = "String", dataTypeClass = String.class),
            @ApiImplicitParam(name = "avatar", value = "头像", dataType = "String", dataTypeClass = String.class),
            @ApiImplicitParam(name = "phone", value = "电话", dataType = "String", dataTypeClass = String.class),
            @ApiImplicitParam(name = "openId", value = "openId", dataType = "String", dataTypeClass = String.class),
    })
    public AjaxResult register(@ApiIgnore @RequestBody Account account) {
        account.setCreateTime(new Date());
        accountService.saveOrUpdate(account);
        String token = loginService.weChatLogin(account.getOpenId());
        accountService.lambdaUpdate()
                .eq(AccountVo::getAccountId,account.getAccountId())
                .set(AccountVo::getToken,token)
                .update();
        return AjaxResult.success("注册成功",token);
    }
    /**
     * 获取用户详细信息
     */
    @GetMapping(value = "/info")
    @ApiOperation("获取用户详细信息")
    public R<Account> getInfo() {
        Account account = accountService.getById(SecurityUtils.getUserId());
        if (account.getVipEnd() != null && account.getVipEnd().before(new Date())){
            account.setVipEnd(null);
            accountService.lambdaUpdate()
                    .eq(AccountVo::getAccountId,account.getAccountId())
                    .set(AccountVo::getVipEnd,null)
                    .update();
        }
        Calendar calendar = Calendar.getInstance();
        calendar.add(Calendar.DAY_OF_MONTH,-15);
        if (account.getVipEnd() != null && StringUtils.isEmpty(account.getVipPopup()) && account.getVipEnd().after(calendar.getTime())){
            account.setVipPopup("1");
            accountService.lambdaUpdate()
                    .eq(AccountVo::getAccountId,account.getAccountId())
                    .set(Account::getVipPopup,"1")
                    .update();
        }
        return R.ok(account);
    }

    /**
     * 修改用户
     */
    @Log(title = "用户", businessType = BusinessType.UPDATE)
    @PostMapping("update")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "name", value = "姓名", dataType = "String", dataTypeClass = String.class),
            @ApiImplicitParam(name = "avatar", value = "头像", dataType = "String", dataTypeClass = String.class),
            @ApiImplicitParam(name = "phone", value = "电话", dataType = "String", dataTypeClass = String.class),
            @ApiImplicitParam(name = "realName", value = "真实名称", dataType = "String", dataTypeClass = String.class),
            @ApiImplicitParam(name = "shopName", value = "店铺名称", dataType = "String", dataTypeClass = String.class),
            @ApiImplicitParam(name = "shopPhone", value = "店铺电话", dataType = "String", dataTypeClass = String.class),
            @ApiImplicitParam(name = "shopAvatar", value = "店铺头像", dataType = "String", dataTypeClass = String.class),
            @ApiImplicitParam(name = "shopAddress", value = "店铺地址", dataType = "String", dataTypeClass = String.class),
            @ApiImplicitParam(name = "shopBusiness", value = "店铺营业时间", dataType = "String", dataTypeClass = String.class),
            @ApiImplicitParam(name = "shopTags", value = "店铺标签", dataType = "String", dataTypeClass = String.class),
            @ApiImplicitParam(name = "shopIntro", value = "店铺简介", dataType = "String", dataTypeClass = String.class),
            @ApiImplicitParam(name = "shopState", value = "店铺状态 传1待审核", dataType = "String", dataTypeClass = String.class),
    })
    @RepeatSubmit
    @ApiOperation("修改用户")
    public AjaxResult edit(@ApiIgnore @RequestBody Account account) {
        account.setAccountId(SecurityUtils.getUserId());
        StringUtils.updateRequired(account);
        accountService.updateAccount(account);
        return success("修改成功");
    }

    @GetMapping(value="getPhone")
    @ApiOperation(value = "根据code获取手机号", notes = "根据code获取手机号")
    public AjaxResult getPhone(String code){
        String accessToken = WxAppletUserInfo.getMPToken(
                configService.selectConfigByKey("wx.appId"),
                configService.selectConfigByKey("wx.secret")
        );
        String url = "https://api.weixin.qq.com/wxa/business/getuserphonenumber?"
                + "access_token=" + accessToken;
        JSONObject js = new JSONObject();
        js.put("code",code);
        JSONObject res = JSONObject.parseObject(HttpUtils.sendPost(url, js.toJSONString()));
        if (res.getInteger("errcode") == 0){
            String phone = res.getJSONObject("phone_info").getString("phoneNumber");
            if ("null".equals(phone))
                phone = "";
            return AjaxResult.success("获取成功",phone);
        }
        return AjaxResult.error();
    }

    @GetMapping(value="getVip")
    @ApiOperation(value = "领取会员", notes = "领取会员")
    public AjaxResult getVip(){
        Setting setting = settingService.lambdaQuery()
                .eq(SettingVo::getGroupKey, "vip")
                .eq(SettingVo::getValueKey, "vipSend")
                .one();
        Calendar calendar = Calendar.getInstance();
        calendar.add(Calendar.DAY_OF_MONTH, Integer.parseInt(setting.getValue()));
        accountService.lambdaUpdate()
                .eq(AccountVo::getAccountId,SecurityUtils.getUserId())
                .set(AccountVo::getVipEnd,calendar.getTime())
                .set(Account::getNewVip,"0")
                .set(Account::getVipPopup,"0")
                .update();
        return success();
    }


}
